"""
批量操作路由
支持批量模型和订阅操作
"""

from fastapi import APIRouter, HTTPException
from typing import List, Dict, Any
from pydantic import BaseModel, ConfigDict

from ..models import BaseResponse
from ..storage import data_manager
from ..logger import logger
from ..services.event_dispatcher import event_dispatcher, EventType

router = APIRouter()


class BatchModelRequest(BaseModel):
    """批量模型请求"""
    model_config = ConfigDict(protected_namespaces=())

    model_ids: List[str]
    operation: str  # 'delete', 'update_status', etc.
    parameters: Dict[str, Any] = {}


class BatchSubscriptionRequest(BaseModel):
    """批量订阅请求"""
    subscription_ids: List[str]
    operation: str  # 'activate', 'pause', 'cancel', 'delete'
    parameters: Dict[str, Any] = {}


class BatchServerRequest(BaseModel):
    """批量服务器请求"""
    server_ids: List[str]
    operation: str  # 'check', 'delete', 'update_interval'
    parameters: Dict[str, Any] = {}


@router.post("/batch/models", response_model=Dict[str, Any])
async def batch_model_operations(request: BatchModelRequest):
    """批量模型操作"""
    try:
        results = {
            "success": 0,
            "failed": 0,
            "errors": [],
            "processed": []
        }
        
        for model_id in request.model_ids:
            try:
                if request.operation == "delete":
                    await _delete_model_batch(model_id, results)
                elif request.operation == "update_status":
                    await _update_model_status_batch(model_id, request.parameters, results)
                else:
                    results["errors"].append(f"Unknown operation: {request.operation}")
                    results["failed"] += 1
                    
            except Exception as e:
                results["errors"].append(f"Model {model_id}: {str(e)}")
                results["failed"] += 1
        
        return {
            "success": True,
            "message": f"Batch operation completed: {results['success']} success, {results['failed']} failed",
            "results": results,
            "timestamp": __import__('time').time()
        }
        
    except Exception as e:
        logger.error(f"Batch model operation failed: {e}")
        raise HTTPException(status_code=500, detail="Batch operation failed")


async def _delete_model_batch(model_id: str, results: Dict):
    """批量删除模型"""
    model = await data_manager.get_model_by_id(model_id)
    if not model:
        results["errors"].append(f"Model {model_id} not found")
        results["failed"] += 1
        return
    
    await data_manager.delete_model(model_id)
    
    # 发出删除事件
    await event_dispatcher.emit(
        EventType.MODEL_DELETED,
        {
            "model_id": model_id,
            "model_name": model.name,
            "model_version": model.version
        },
        "batch_operation"
    )
    
    results["processed"].append({
        "model_id": model_id,
        "model_name": model.name,
        "operation": "deleted"
    })
    results["success"] += 1


async def _update_model_status_batch(model_id: str, parameters: Dict, results: Dict):
    """批量更新模型状态"""
    model = await data_manager.get_model_by_id(model_id)
    if not model:
        results["errors"].append(f"Model {model_id} not found")
        results["failed"] += 1
        return
    
    new_status = parameters.get("status", "available")
    model.status = new_status
    model.last_update = __import__('time').time()
    
    await data_manager.update_model(model)
    
    results["processed"].append({
        "model_id": model_id,
        "model_name": model.name,
        "operation": "status_updated",
        "new_status": new_status
    })
    results["success"] += 1


@router.post("/batch/subscriptions", response_model=Dict[str, Any])
async def batch_subscription_operations(request: BatchSubscriptionRequest):
    """批量订阅操作"""
    try:
        results = {
            "success": 0,
            "failed": 0,
            "errors": [],
            "processed": []
        }
        
        for subscription_id in request.subscription_ids:
            try:
                if request.operation == "delete":
                    await _delete_subscription_batch(subscription_id, results)
                elif request.operation in ["activate", "pause", "cancel"]:
                    await _update_subscription_status_batch(
                        subscription_id, request.operation, results
                    )
                else:
                    results["errors"].append(f"Unknown operation: {request.operation}")
                    results["failed"] += 1
                    
            except Exception as e:
                results["errors"].append(f"Subscription {subscription_id}: {str(e)}")
                results["failed"] += 1
        
        return {
            "success": True,
            "message": f"Batch operation completed: {results['success']} success, {results['failed']} failed",
            "results": results,
            "timestamp": __import__('time').time()
        }
        
    except Exception as e:
        logger.error(f"Batch subscription operation failed: {e}")
        raise HTTPException(status_code=500, detail="Batch operation failed")


async def _delete_subscription_batch(subscription_id: str, results: Dict):
    """批量删除订阅"""
    subscription = await data_manager.get_subscription_by_id(subscription_id)
    if not subscription:
        results["errors"].append(f"Subscription {subscription_id} not found")
        results["failed"] += 1
        return
    
    await data_manager.delete_subscription(subscription_id)
    
    # 发出删除事件
    await event_dispatcher.emit(
        EventType.SUBSCRIPTION_DELETED,
        {
            "subscription_id": subscription_id,
            "client_id": subscription.client_id,
            "model_name": subscription.model_name
        },
        "batch_operation"
    )
    
    results["processed"].append({
        "subscription_id": subscription_id,
        "client_id": subscription.client_id,
        "model_name": subscription.model_name,
        "operation": "deleted"
    })
    results["success"] += 1


async def _update_subscription_status_batch(subscription_id: str, operation: str, results: Dict):
    """批量更新订阅状态"""
    subscription = await data_manager.get_subscription_by_id(subscription_id)
    if not subscription:
        results["errors"].append(f"Subscription {subscription_id} not found")
        results["failed"] += 1
        return
    
    # 映射操作到状态
    status_map = {
        "activate": "active",
        "pause": "paused",
        "cancel": "cancelled"
    }
    
    new_status = status_map.get(operation)
    if not new_status:
        results["errors"].append(f"Invalid operation: {operation}")
        results["failed"] += 1
        return
    
    subscription.status = new_status
    subscription.last_checked = __import__('time').time()
    
    await data_manager.update_subscription(subscription)
    
    # 发出更新事件
    await event_dispatcher.emit(
        EventType.SUBSCRIPTION_UPDATED,
        {
            "subscription_id": subscription_id,
            "client_id": subscription.client_id,
            "model_name": subscription.model_name,
            "new_status": new_status
        },
        "batch_operation"
    )
    
    results["processed"].append({
        "subscription_id": subscription_id,
        "client_id": subscription.client_id,
        "model_name": subscription.model_name,
        "operation": f"status_updated_to_{new_status}"
    })
    results["success"] += 1


@router.post("/batch/servers", response_model=Dict[str, Any])
async def batch_server_operations(request: BatchServerRequest):
    """批量服务器操作"""
    try:
        results = {
            "success": 0,
            "failed": 0,
            "errors": [],
            "processed": []
        }
        
        for server_id in request.server_ids:
            try:
                if request.operation == "check":
                    await _check_server_batch(server_id, results)
                elif request.operation == "delete":
                    await _delete_server_batch(server_id, results)
                elif request.operation == "update_interval":
                    await _update_server_interval_batch(server_id, request.parameters, results)
                else:
                    results["errors"].append(f"Unknown operation: {request.operation}")
                    results["failed"] += 1
                    
            except Exception as e:
                results["errors"].append(f"Server {server_id}: {str(e)}")
                results["failed"] += 1
        
        return {
            "success": True,
            "message": f"Batch operation completed: {results['success']} success, {results['failed']} failed",
            "results": results,
            "timestamp": __import__('time').time()
        }
        
    except Exception as e:
        logger.error(f"Batch server operation failed: {e}")
        raise HTTPException(status_code=500, detail="Batch operation failed")


async def _check_server_batch(server_id: str, results: Dict):
    """批量检查服务器"""
    server = await data_manager.get_server_by_id(server_id)
    if not server:
        results["errors"].append(f"Server {server_id} not found")
        results["failed"] += 1
        return
    
    # 这里应该调用实际的服务器检查逻辑
    # 目前只是模拟
    server.last_check = __import__('time').time()
    await data_manager.update_server(server)
    
    results["processed"].append({
        "server_id": server_id,
        "server_name": server.name,
        "operation": "checked",
        "status": server.status
    })
    results["success"] += 1


async def _delete_server_batch(server_id: str, results: Dict):
    """批量删除服务器"""
    server = await data_manager.get_server_by_id(server_id)
    if not server:
        results["errors"].append(f"Server {server_id} not found")
        results["failed"] += 1
        return
    
    await data_manager.delete_server(server_id)
    
    results["processed"].append({
        "server_id": server_id,
        "server_name": server.name,
        "operation": "deleted"
    })
    results["success"] += 1


async def _update_server_interval_batch(server_id: str, parameters: Dict, results: Dict):
    """批量更新服务器检查间隔"""
    server = await data_manager.get_server_by_id(server_id)
    if not server:
        results["errors"].append(f"Server {server_id} not found")
        results["failed"] += 1
        return
    
    new_interval = parameters.get("check_interval", 1800)
    server.check_interval = new_interval
    
    await data_manager.update_server(server)
    
    results["processed"].append({
        "server_id": server_id,
        "server_name": server.name,
        "operation": "interval_updated",
        "new_interval": new_interval
    })
    results["success"] += 1
